<template>
  <view class="page ui-form-basic">
    <fui-form ref="formRef" :model="form" class="form-wrapper" labelWidth="200" labelSize="28" labelWeight="bold">
      <fui-form-item label="物流公司" prop="wlgsid" left="0" marginTop="14" :padding="['16rpx', 0]" @click="showDeliveryPicker = true" arrow>
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择物流公司" v-model="form.wlgsmc" disabled></fui-input>
      </fui-form-item>
      <fui-form-item label="物流人员" prop="wlrymc" left="0" marginTop="14" :padding="['16rpx', 0]">
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入物流人员" v-model="form.wlrymc"></fui-input>
      </fui-form-item>
      <fui-form-item label="联系方式" prop="wlrysjh" left="0" marginTop="14" :padding="['16rpx', 0]">
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入联系方式" v-model="form.wlrysjh"></fui-input>
      </fui-form-item>
      <fui-form-item label="上传物流单" prop="wldh" left="0" marginTop="14" :padding="['16rpx', 0]">
        <upload-image type="avatar" :max="1" @uploaded="uploadedDelivery">
        </upload-image>
      </fui-form-item>
      <fui-form-item label="物流单号" prop="wldh" left="0" marginTop="14" :padding="['16rpx', 0]">
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入物流单号" v-model="form.wldh" :maxlength="20"></fui-input>
      </fui-form-item>
      <fui-form-item label="备注信息" prop="bz" left="0" marginTop="14" :padding="['16rpx', 0]">
        <template v-slot:vertical>
          <fui-textarea size="28" :maxlength="50" height="64rpx" :isCounter="true" radius="16" borderColor="#DFDFDF" v-model="form.bz" placeholder="请输入备注信息" textareaBorder></fui-textarea>
        </template>
      </fui-form-item>
    </fui-form>

    <!-- 商品清单 -->
    <view class="goods-list-wrapper">
      <view class="goods-list-header">
        <fui-text text="商品清单" size="28" fontWeight="bold" color="#333"></fui-text>
        <fui-button class="ui-btn-primary_plain" text="选择商品" width="120rpx" height="48rpx" radius="8rpx" size="24" @click="tab.navigateTo(goodsLink)"></fui-button>
      </view>
      <view class="goods-list-content" v-show="checkedGoodsList.length">
        <!-- <fui-empty src="/static/images/empty/data.png" title="暂无商品" width="240" height="120" size="28" color="#999"></fui-empty> -->
        <view class="goods-list">
          <view class="goods-item" v-for="item in checkedGoodsList">
            <image class="goods-item-image" :src="item.picUrl"></image>
            <view class="goods-item-info">
              <view class="goods-item-title">{{ item.spuName }}</view>
              <view class="goods-item-num">x {{ item.count }}</view>
            </view>
          </view>
        
        </view>
      </view>
    </view>

    <view class="btn-wrapper">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
      <fui-button text="确认发货" height="78rpx" radius="8rpx" :margin="['0']" @click="handleSubmit"></fui-button>
    </view>

    <!-- 物流公司 -->
    <fui-picker layer="1" @cancel="showDeliveryPicker = false" radius :options="deliveryData" :fields="['name', 'id']" linkage :show="showDeliveryPicker" @change="onChangeDelivery"></fui-picker>
  </view>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import uploadImage from '@/components/upload/image'
import orderApi from '@/api/order'
import deliveryApi from '@/api/delivery'
import { useStore } from 'vuex'

const store = useStore()

const tab = inject('$tab')
const modal = inject('$modal')
const checkedGoodsIds = ref(0)

const orderId = ref('')
const deliveryId = ref('')
onLoad((option) => {
  orderId.value = option.orderId
  deliveryId.value = option.deliveryId
  getDeliveryList()
})

// 发货表单信息
const formRef = ref(null)
const form = reactive({
  wlgsid: '',
  wlgsmc: '',
  wlrymc: '',
  wlrysjh: '',
  wldh: '',
  orderId: orderId.value,
  orderItemIds:[]
})
const rules = [
  {
    name: 'wlgsid',
    rule: ['required'],
    msg: ['请选择物流公司']
  },
  {
    name: 'wlrymc',
    rule: ['required'],
    msg: ['请输入物流人员']
  },
  {
    name: 'wlrysjh',
    rule: ['required', 'isMobile'],
    msg: ['请输入联系方式', '请输入正确的手机号']
  },
  {
    name: 'wldh',
    rule: ['required'],
    msg: ['请输入物流单号']
  }
]

// 物流公司
const deliveryData = ref([])
const getDeliveryList = async () => {
  try {
    await orderApi.getDeliveryList().then((res) => {
      if (res.code === 0) {
        deliveryData.value = res.data || []
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.msgError('获取物流公司数据失败')
  }
}
const showDeliveryPicker = ref(false)
const onChangeDelivery = (e) => {
  showDeliveryPicker.value = false
  form.wlgsid = e.value
  form.wlgsmc = e.text
}

// 上传物流单
const uploadedDelivery = async(e) => {
  console.log("aaaaaaaaaaaaaaaaaaaaaa",e[0])
	if(e[0]){
		const res = await deliveryApi.getFreeLabel(e[0])
		if(res.code == 0){
      console.log('sssssssss', res.data)
			form.wldh = res.data
			// console.log(addStoreData.value.wldh);
		}
	}
}

// 商品清单
// const goodsList = computed(() => store.getters.deliveryGoodsList)
const goodsList = ref([])

// const checkedGoodsList = computed(() => goodsList.value.filter(item => checkedGoodsIds.value.indexOf(item.id) > -1))
const checkedGoodsList = ref([])
const goodsLink = computed(() => {
  if (checkedGoodsIds.value.length) {
    return `/pages/delivery/goods?orderId=${orderId.value}&checkedGoodsIds=${checkedGoodsIds.value.join(',')}`
  } else {
    return `/pages/delivery/goods?orderId=${orderId.value}`
  }
})
onShow(() => {
  uni.$once('onCheckedGoods', ids => {
    checkedGoodsIds.value = ids
    getGoodsList()
  })
})


// 查询商品列表
const getGoodsList = () => {
  modal.loading('加载中...')
  try{
    orderApi.getOrderDetail(orderId.value).then((res) => {
      modal.closeLoading();
      if(res.code === 0){
        goodsList.value = res.data.items.map((item) => {
          return {
            ...item
          };
        });
        handleCheckedGoods()
      }else{
        modal.msgError(res.msg);
      }
    })
  }catch(e){
    modal.closeLoading();
    modal.msgError(e.msg);
  }
}

// 确定已选中的商品列表
const handleCheckedGoods = () => {
  checkedGoodsList.value = goodsList.value.filter(item => checkedGoodsIds.value.indexOf(item.id + '') > -1)
}

// 提交表单方法
const handleSubmit = async () => {
  if (!checkedGoodsIds.value.length) {
    modal.msgError('请至少选择一个关联商品！')
    return
  }

  try {
    const validRes = await formRef.value.validator(form, rules)
    form.orderItemIds = checkedGoodsIds.value
    form.orderId = orderId.value
    if (validRes.isPassed) {
      deliveryApi.addDelivery(form).then((res) => {
        if (res.code === 0) {
          modal.msg('提交成功！')
          store.commit('SET_DELIVERY_ORDERINFO', null)
          setTimeout(() => {
            uni.navigateBack({
              delta: 2
            })
          }, 1000)
          // tab.navigateTo(`/pages/delivery/index?orderId=${orderId.value}`)
        } else {
          modal.msgError(res.msg)
        }
      })
    }
  } catch (err) {
    modal.msgError('发货失败！')
  }
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.goods-list-wrapper {
  margin-top: 10rpx;
  .goods-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
  }
  .goods-list-content {
    border-radius: 8rpx;
    background-color: #fff;
    padding: 24rpx;
    ::v-deep .fui-empty__wrap {
      padding: 24rpx 0;
      .fui-empty__title {
        padding-top: 10rpx;
      }
    }
    .goods-list {
      overflow: hidden;
      border-radius: 16rpx;
      background-color: #fff;
      .goods-item {
        display: flex;
        align-items: center;
        padding: 28rpx 0 !important;
        &:not(:last-child) {
          border-bottom: 2rpx solid var(--fui-color-border);
        }
        .goods-item-image {
          flex: 0 0 132rpx;
          width: 132rpx;
          height: 132rpx;
          overflow: hidden;
          border-radius: 8rpx;
          background: #f8f8f8;
          margin-right: 24rpx;
        }
        .goods-item-info {
          flex: 1;
          .goods-item-title {
            margin-bottom: 5rpx;
            font-size: 24rpx;
            font-weight: bold;
            color: #333;
          }
          .goods-item-num {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
    }
  }
}

.btn-wrapper {
  margin-top: 80rpx !important;
}
</style>
